<template>
  <div>
    <!-- 表单 -->
    <div class="gantt-head">
      <el-form class="search-form" :model="formInline" ref="ruleFormRef">
        <template v-for="(item, index) in formSearchData" :key="index">
          <el-form-item :label="item.label">
            <!-- 下拉选择框 -->
            <template v-if="item.valueType === 'select'">
              <el-select
                v-model="formInline[item.name]"
                :placeholder="`请选择${item.label}`"
                clearable
                style="margin-right: 10px"
              >
                <el-option
                  v-for="ite in item.options"
                  :key="ite.value"
                  :label="ite.label"
                  :value="ite.value"
                />
              </el-select>
            </template>
          </el-form-item>
        </template>
      </el-form>
      <div class="legend">
        <div class="legendBox">
          <div class="legendSml legendColor1"></div>
          <div class="text">计划时间</div>
        </div>
        <div class="legendBox">
          <div class="legendSml legendColor3"></div>
          <div class="text">实际时间</div>
        </div>
      </div>
      <div class="search">
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="reset(ruleFormRef)">重置</el-button>
      </div>
    </div>

    <div
      ref="ganttRef"
      id="gantt_here"
      style="min-height: calc(85vh - 100px); width: 100%; overflow: hidden"
    ></div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
// import { gantt } from "dhtmlx-gantt"; // 引入dhtmlx-gantt
// import "dhtmlx-gantt/codebase/dhtmlxgantt.css"; //皮肤

import dayjs from "dayjs";
const ganttRef = ref();

const props = defineProps({
  // 任务对象
  tasks: {
    type: Object,
    default: () => {
      return {
        data: [], //数据数组
        links: [], //连接关系
      };
    },
  },

  // 显示列设置
  columns: {
    type: Array,
    default: () => {
      return [];
    },
  },
  //表单搜素的配置
  formColumns: {
    type: Array,
    default: () => {
      return [];
    },
  },

  // 显示单位
  scaleUnit: {
    type: String,
    default: "day", //“minute”, “hour”, “day”, “week”, “quarter”, “month”, “year”
  },

  // 时间显示格式
  dateScale: {
    type: String,
    default: "%Y-%m-%d", //%d/%m/%Y
  },
});

let obj = {};

let search = [];
const formInline = reactive(obj);

const formSearchData = ref(search);

const onSubmit = () => {
  for (let key in formInline) {
    switch (formInline[key]) {
      case "year":
        switchToYear();
        break;
      case "month":
        switchToMonth();
        break;
      case "day":
        switchToDay();
        break;
      default:
        break;
    }
  }

  emit("onSubmit", formInline);
};

const reset = () => {
  formSearchData.value.forEach((item) => {
    formInline[item.name] = null;
  });
  emit("rest", formInline);
};

const emit = defineEmits(["onSubmit", "reset", "initDate"]);

for (let item of props.formColumns) {
  if (item.inSearch) {
    obj[item.name] = null;
  }
  if (item.inSearch) {
    search.push(item);
  }
}

gantt.templates.task_class = function (start, end, task) {
  if (task.planned_end) {
    return classes.join("class-name");
  }
};

//  年 月 日 切换
const switchToYear = () => {
  gantt.config.scales = [{ unit: "year", step: 1, format: "%Y年" }];
  gantt.render();
};

const switchToMonth = () => {
  gantt.config.scales = [
    { unit: "year", step: 1, format: "%Y年" },
    { unit: "month", step: 1, date: "%m月" },
  ];
  gantt.render();
};

const switchToDay = () => {
  gantt.config.scales = [
    { unit: "month", step: 1, format: "%m月" },
    { unit: "day", step: 1, date: "%d日" },
  ];
  gantt.render();
};

function getGanttZoomConfig() {
  const monthFormat = function (date) {
    // console.log(date);
    return `${dayjs(date).format("YYYY-MM")}`;
  };
  const dayFormat = function (date) {
    return `${dayjs(date).format("MM-DD")}`;
  };
  const hourFormat = function (date) {
    return `${dayjs(date).format("HH:mm")}`;
  };
  const hourToStr = gantt.date.date_to_str("%H:%i");
  const rangeFormat = function (type, step) {
    return function (date) {
      const intervalEnd = new Date(gantt.date.add(date, step, type));
      return hourToStr(date) + " - " + hourToStr(intervalEnd);
    };
  };
  return {
    minColumnWidth: 80,
    maxColumnWidth: 150,
    levels: [
      [
        { unit: "year", format: monthFormat, step: 1 },
        { unit: "month", format: dayFormat, step: 1 },
      ],
      [
        { unit: "month", format: monthFormat, step: 1 },
        { unit: "day", format: dayFormat, step: 15 },
      ],
      [
        { unit: "month", format: monthFormat, step: 1 },
        { unit: "day", format: dayFormat, step: 7 },
      ],
      [
        { unit: "month", format: monthFormat, step: 1 }, 
        { unit: "day", format: dayFormat, step: 1 },
      ],
      // [
      //   { unit: "day", format: dayFormat, step: 1 },
      //   { unit: "hour", format: rangeFormat("hour", 12), step: 12 },
      // ],
      // [
      //   { unit: "day", format: dayFormat, step: 1 },
      //   { unit: "hour", format: rangeFormat("hour", 6), step: 6 },
      // ],
      // [
      //   { unit: "day", format: dayFormat, step: 1 },
      //   { unit: "hour", format: hourFormat, step: 1 },
      // ],
      // [
      //   { unit: 'hour', format: hourFormat, step: 1 },
      //   { unit: 'minute', format: rangeFormat('minute', 45), step: 45 },
      // ],
      // [
      //   { unit: 'hour', format: hourFormat, step: 1 },
      //   { unit: 'minute', format: rangeFormat('minute', 30), step: 30 },
      // ],
      // [
      //   { unit: 'hour', format: hourFormat, step: 1 },
      //   { unit: 'minute', format: rangeFormat('minute', 15), step: 15 },
      // ],
      // [
      //   { unit: 'hour', format: hourFormat, step: 1 },
      //   { unit: 'minute', format: rangeFormat('minute', 5), step: 5 },
      // ],
      // [
      //   { unit: 'hour', format: hourFormat, step: 1 },
      //   { unit: 'minute', format: '%H:%i', step: 1 },
      // ],
    ],
    trigger: "wheel",
    activeLevelIndex: 2,
    element: function () {
      return gantt.$root.querySelector(".gantt_task");
    },
  };
}

// 开启marker插件
gantt.plugins({ marker: true, tooltip: true });
var dateToStr = gantt.date.date_to_str("%Y-%m-%d"); // 自定义日期格式
const today = new Date(dayjs(new Date()).format("YYYY-MM-DD"));

onMounted(async () => {
  //------- 清空之前的配置-------
  gantt.clearAll();
  //任务条上的文字大小 以及取消border自带样式
  // gantt.templates.task_class = function () {
  //   return "firstLevelTask";
  // };
 

  // 添加固定时间线
  // gantt.addMarker({
  //   start_date: new Date(),
  //   css: "today",
  //   text: "今日:" + dayjs(new Date()).format("YYYY-MM-DD"),
  //   title: "Today: " + dateToStr(today),
  // });
  const zoomConfig = getGanttZoomConfig();
  // console.log(zoomConfig,'123')
  gantt.ext.zoom.init(zoomConfig);

  // gantt图布局设计 本例使用_scrollable_grid布局，方便多时间跨度查看
  // gantt.config.layout = {
  //   css: "gantt_container",
  //   cols: [
  //     {
  //       width: 500,
  //       min_width: 300,
  //       rows: [
  //         {
  //           view: "grid",
  //           scrollX: "gridScroll",
  //           scrollable: true,
  //           scrollY: "scrollVer",
  //         },
  //         { view: "scrollbar", id: "gridScroll", group: "horizontal" },
  //       ],
  //     },
  //     { resizer: true, width: 1 },
  //     {
  //       rows: [
  //         {
  //           view: "timeline",
  //           scrollX: "scrollHor",
  //           scrollable: true,
  //           scrollY: "scrollVer",
  //         },
  //         { view: "scrollbar", id: "scrollHor", group: "horizontal" },
  //       ],
  //     },
  //     { view: "scrollbar", id: "scrollVer" },
  //   ],
  // }


  gantt.config.task_height = 16;
  gantt.config.row_height = 40;
  gantt.config.min_column_width = 40; //下面日期的宽度，会随时间长短宽度变化。但是设置最小宽度后，当时间跨度到达一定长度，就会展示最小宽度。

  // 表头高度
  // gantt.config.scale_height = 90;
  // 甘特图以自动扩展时间范围，以适应所有显示的任务
  // gantt.config.fit_tasks = true;
  //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
  gantt.config.show_task_cells = true;

  gantt.config.date_format = "%Y-%m-%d";
  // 默认配置
  gantt.config.xml_date = "%Y-%m-%d";

  // 设置中文
  gantt.i18n.setLocale("cn");

  // 设置为只读
  gantt.config.readonly = true;
  //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
  gantt.config.autosize = true;
  //甘特图图表宽度自适应
  gantt.config.autofit = true;
  // 开启网格
  gantt.config.show_grid = true;

  // 显示列配置
  gantt.config.columns = props.columns;

  //   网络图部分表头格式化
  // gantt.config.scales = [
  //   // { unit: "year", step: 1, date: "%Y年" },
  //   { unit: "month", step: 1, date: "%Y-%m" },
  //   { unit: "day", step: 1, date: "%m-%d" },
  // ];

  gantt.config.show_grid = true;

  // 初始化甘特图
  await gantt.init(ganttRef.value);
  // 渲染数据
  await gantt.parse(props.tasks);
});
</script>
<style  >
.gantt_grid_head_cell {
  background-color: #f5f7fa !important;
}
.gantt_scale_line {
  background-color: #f5f7fa !important;
}
.gantt_scale_cell {
  /* width: 30px !important; */
  /* left:70px !important; */
}
</style>
<style scoped lang="scss">
.gantt-head {
  display: flex;
  justify-content: space-between;
}
.search-form {
  display: flex;
}
.legend {
  padding: 0px 0px 5px 0px;
  display: flex;
  .legendBox {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
  .legendSml {
    width: 30px;
    height: 16px;
    border-radius: 5px;
    margin-right: 4px;
  }
  .legendColor1 {
    border-radius: 8px;
    height: 10px;
    background-color: #3b97fe !important;
  }
  .legendColor3 {
    border-radius: 8px;
    height: 10px;
    background-color: #ffd180 !important;
  }
}
</style>
